#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import re
import pandas as pd
from collections import defaultdict
import sys


def parse_jit_log_advanced(log_file_path):
    """
    高级解析JIT编译日志文件，支持多个用例

    Args:
        log_file_path: 日志文件路径

    Returns:
        tuple: (case_data, summary_data, method_summary, phase_data)
    """
    # 初始化数据结构
    case_data = []  # 表1数据: case, method, pass, time, input, output
    summary_data = defaultdict(
        lambda: {"total_time": 0, "total_input": 0, "total_output": 0, "count": 0}
    )
    method_summary = defaultdict(lambda: {"total_time": 0, "pass_count": 0})
    phase_data = {"midend_time": 0, "backend_time": 0, "total_time": 0}

    current_case = None
    current_method = None
    current_phase = "midend"  # 初始为中端pass

    # 正则表达式模式
    case_pattern = re.compile(r"ark_js_vm.*--entry-point=\S+.*?(\S+)\.abc")
    method_pattern = re.compile(
        r"\[jit\]\s*\[fastjit\]\s*compile\s*method:([^:]+):([^,]+), in jit thread begin.$"
    )
    pass_pattern = re.compile(
        r"\[compiler\]\s*\[ekil\]\s*(\w+)\s+([\d\.]+)(?:\s+(\d+)(?:\s+(\d+))?)?$"
    )
    phase_pattern = re.compile(
        r"\[compiler\]\s*==============\s*building litecg ir\s*==============$"
    )

    with open(log_file_path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()

            # 解析用例名 (case)
            case_match = case_pattern.search(line)
            if case_match:
                case_name = case_match.group(1)
                current_case = f"{case_name}.js"
                print(f"Found case: {current_case}")
                continue

            # 解析方法名 (method)
            method_match = method_pattern.search(line)
            if method_match:
                current_method = method_match.group(2)
                current_phase = "midend"  # 新方法开始时重置为中端
                print(f"Found method: {current_method}")
                continue

            # 检测phase分界线 (中端 -> 后端)
            phase_match = phase_pattern.search(line)
            if phase_match:
                current_phase = "backend"
                print(f"Phase changed to: {current_phase}")
                continue

            # 解析编译pass信息
            pass_match = pass_pattern.search(line)
            if pass_match and current_case and current_method:
                pass_name = pass_match.group(1)
                time = float(pass_match.group(2))

                # 处理不同的数据格式
                input_nodes = 0
                output_nodes = 0

                if pass_match.group(3):  # 有输入节点数据
                    input_nodes = int(pass_match.group(3))
                    if pass_match.group(4):  # 有输出节点数据
                        output_nodes = int(pass_match.group(4))

                # 添加到表1数据
                case_data.append(
                    {
                        "case": current_case,
                        "method": current_method,
                        "pass": pass_name,
                        "phase": current_phase,
                        "time": time,
                        "input": input_nodes,
                        "output": output_nodes,
                    }
                )

                # 更新汇总数据（按pass名称聚合）
                summary_data[pass_name]["total_time"] += time
                summary_data[pass_name]["total_input"] += input_nodes
                summary_data[pass_name]["total_output"] += output_nodes
                summary_data[pass_name]["phase"] = current_phase
                summary_data[pass_name]["count"] += 1

                # 更新phase数据
                if current_phase == "midend":
                    phase_data["midend_time"] += time
                else:
                    phase_data["backend_time"] += time
                phase_data["total_time"] += time

                # 更新方法汇总数据
                method_key = f"{current_case}.{current_method}"
                method_summary[method_key]["total_time"] += time
                method_summary[method_key]["pass_count"] += 1

    return case_data, summary_data, method_summary, phase_data


def create_advanced_excel_output(
    case_data, summary_data, method_summary, phase_data, output_file
):
    """
    创建高级Excel输出文件，包含多个工作表

    Args:
        case_data: 表1数据
        summary_data: 汇总数据
        method_summary: 方法汇总数据
        phase_data: phase统计数据
        output_file: 输出文件路径
    """
    # 创建表1: 详细数据
    df_case = pd.DataFrame(case_data)

    # 创建表2: 编译pass汇总统计
    summary_list = []
    for pass_name, data in summary_data.items():
        summary_list.append(
            {
                "pass": pass_name,
                "phase": data["phase"],
                "总耗时": round(data["total_time"], 2),
                "总输入节点": data["total_input"],
                "总输出节点": data["total_output"],
                "执行次数": data["count"],
            }
        )

    df_summary = pd.DataFrame(summary_list)

    # 创建表3: 方法汇总统计
    method_list = []
    for method_key, data in method_summary.items():
        case, method = method_key.rsplit(".", 1)
        method_list.append(
            {
                "用例": case,
                "方法": method,
                "总编译耗时": round(data["total_time"], 2),
                "编译pass数量": data["pass_count"],
                "平均每个pass耗时": round(
                    (
                        data["total_time"] / data["pass_count"]
                        if data["pass_count"] > 0
                        else 0
                    ),
                    2,
                ),
            }
        )

    df_method_summary = pd.DataFrame(method_list)

    # 创建表4: Phase耗时分析
    if phase_data["total_time"] > 0:
        midend_percentage = (phase_data["midend_time"] / phase_data["total_time"]) * 100
        backend_percentage = (
            phase_data["backend_time"] / phase_data["total_time"]
        ) * 100
    else:
        midend_percentage = backend_percentage = 0

    phase_list = [
        {
            "编译阶段": "中端",
            "总耗时(ms)": round(phase_data["midend_time"], 2),
            "占比(%)": round(midend_percentage, 2),
        },
        {
            "编译阶段": "后端",
            "总耗时(ms)": round(phase_data["backend_time"], 2),
            "占比(%)": round(backend_percentage, 2),
        },
        {
            "编译阶段": "总计",
            "总耗时(ms)": round(phase_data["total_time"], 2),
        },
    ]

    df_phase_analysis = pd.DataFrame(phase_list)

    # 写入Excel文件
    with pd.ExcelWriter(output_file, engine="openpyxl") as writer:
        df_case.to_excel(writer, sheet_name="详细编译数据", index=False)
        df_summary.to_excel(writer, sheet_name="编译Pass汇总", index=False)
        df_method_summary.to_excel(writer, sheet_name="方法汇总", index=False)
        df_phase_analysis.to_excel(writer, sheet_name="Phase分析", index=False)

        # 添加数据透视表
        if not df_case.empty:
            pivot_table = pd.pivot_table(
                df_case,
                values=["time", "input", "output"],
                index=["case", "method"],
                columns=["pass"],
                aggfunc="sum",
                fill_value=0,
            )
            pivot_table.to_excel(writer, sheet_name="数据透视表")

            # 添加phase维度的数据透视表
            phase_pivot = pd.pivot_table(
                df_case, values=["time"], index=["phase"], aggfunc="sum", fill_value=0
            )
            phase_pivot.to_excel(writer, sheet_name="Phase透视表")

    print(f"Excel文件已生成: {output_file}")
    print(f"详细编译数据: {len(df_case)} 行")
    print(f"编译Pass汇总: {len(df_summary)} 个编译pass")
    print(f"方法汇总: {len(df_method_summary)} 个方法")
    print(
        f"Phase分析: 中端 {round(phase_data['midend_time'], 2)}ms, 后端 {round(phase_data['backend_time'], 2)}ms"
    )


def main():
    if len(sys.argv) != 3:
        print("用法: python parse_jit_log_advanced.py <输入日志文件> <输出Excel文件>")
        print("示例: python parse_jit_log_advanced.py t.log jit_analysis_advanced.xlsx")
        sys.exit(1)

    log_file = sys.argv[1]
    output_file = sys.argv[2]

    print(f"开始解析日志文件: {log_file}")

    try:
        case_data, summary_data, method_summary, phase_data = parse_jit_log_advanced(
            log_file
        )

        if not case_data:
            print("警告: 未找到任何编译数据，请检查日志文件格式")
            return

        create_advanced_excel_output(
            case_data, summary_data, method_summary, phase_data, output_file
        )

        # 显示一些统计信息
        print("\n解析完成!")
        print(f"共解析 {len(set([d['case'] for d in case_data]))} 个用例")
        print(f"共解析 {len(set([d['method'] for d in case_data]))} 个方法")
        print(f"共解析 {len(set([d['pass'] for d in case_data]))} 个编译pass")

        # 显示耗时最长的编译pass
        if summary_data:
            max_time_pass = max(summary_data.items(), key=lambda x: x[1]["total_time"])
            print(
                f"耗时最长的编译pass: {max_time_pass[0]} ({round(max_time_pass[1]['total_time'], 2)}ms)"
            )

    except Exception as e:
        print(f"解析过程中出现错误: {e}")
        import traceback

        traceback.print_exc()


if __name__ == "__main__":
    main()
